#!/user/bin/python
# coding=utf-8
# 查看模块是否已经成功联网
from time import sleep
import re
import sys
import test
import os
from subprocess import Popen, PIPE, STDOUT
import serial
execfile("../cfg/at/other.cfg")


def execute(cmd):
    ret = []
    proc = Popen([cmd], shell=True, stdout=PIPE, stderr=PIPE)
    for i in list(filter(None, proc.stderr.read().decode('ascii').split('\n'))):
        print i
    for i in list(filter(None, proc.stdout.read().decode('ascii').split('\n'))):
        ret.append(i)
    return '\n'.join(ret)

def del_def_route():
    for i in execute('route | grep default').split('\n'):
        execute('route del default')


def get_dev_and_ip():
    execute('echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter')
    for i in execute('ip -o -4 addr show | awk \'{print $2" "$4}\'').split('\n'):
        dev_ip = i.split(' ')
        execute('echo 0 > /proc/sys/net/ipv4/conf/{}/rp_filter'.format(dev_ip[0]))
        if 'lo' in dev_ip[0]:
            continue
        if 'ppp0' in dev_ip[0]:
            execute('route add default {}'.format(dev_ip[0]))
            continue
        ips = dev_ip[1].split('.')
        ips[3] = '1'
        ip = '.'.join(ips)
        execute('route add default gw {} {}'.format(ip, dev_ip[0]))
        return execute('../bin/dev_name rndis')



def ser_is_ok(dev_port):
    ser = ''
    while True:
        try:
            ser = serial.Serial(port=dev_port, baudrate=115200, timeout=1)
            return ser
        except:
            print('open port '+dev_port+' fail...')
            sleep(5)


def at_command_parse(ser, str1, timeout):
    ser.write(str1)
    count = timeout*10
    read_buf = ""
    while True:
        out_str = ser.read(1024)
        if out_str:
            read_buf = read_buf + out_str
            out_str = ""
        else:
            count -= 1
            if read_buf != "":
                return read_buf
        if count == 0:
            if read_buf == "":
                return "timeout"
            else:
                return read_buf
        sleep(0.1)


def net_is_ok(com):
    read_buf = ''
    count = 1
    is_1802s = False
    print 'check net is ok.....'
    read_buf = at_command_parse(com, "ATI\r\n", 2)
    if read_buf.find("720S") != -1:
        is_1802s = True
        read_buf = ""
    while True:
        if is_1802s:
            read_buf = at_command_parse(com, 'AT+CEREG?\r\n', 1)
            print read_buf
            if 'ERROR' in read_buf:
                continue
            result = re.findall(r'\+CEREG: [0-9],([0-9])', read_buf)
            if int(result[0]) == 1:
                print 'net_is_ok'
                break
        else:
            read_buf = at_command_parse(com, 'AT+CGREG?\r\n', 1)
            print read_buf
            if 'ERROR' in read_buf:
                continue
            result = re.findall(r'\+CGREG: [0-9],([0-9])', read_buf)
            if int(result[0]) == 1:
                print 'net_is_ok'
                break
        sleep(5)
    return True


def close_all_net():
    print "关闭所有网卡"
    rndis = ""
    cmd = os.popen("ifconfig -a").read()
    wlan = re.findall("(wlan[0-9]+)", cmd)
    if wlan:
        for i in range(len(wlan)):
            os.system("ifconfig "+wlan[i]+" down")  # 禁掉无线网卡
    net_card = re.findall("(eth[0-9]+)", cmd)
    if net_card:
        for i in range(len(net_card)):
            os.system("ifconfig "+net_card[i]+" down")
            if net_card[i] != "eth0":
                rndis = net_card[i]
    result = re.findall(r'(enxac[a-z0-9]{10})', cmd)
    if result:
        rndis = result[0]
    return rndis


def set_all_net():
    print "setup gateway per interface"
    # del_def_route()
    # rndis = get_dev_and_ip()
    execute('../cfg/net/del_default_route.sh')
    rndis = execute('../cfg/net/get_dev_and_ip.sh')
    if 'eth' in rndis or 'usb' in rndis or 'enx' in rndis:
        pass
    else:
        rndis = ""
    return rndis


def ping_test(result, ping_str, ping_loop):
    out_str = os.popen(ping_str).read()
    out_result = re.findall("([0-9]+) received, ([0-9]+)", out_str)
    test_str = result.get_test_mode()
    if out_result:
        result.add_ping(ping_loop)
        result.add_ping_suc(int(out_result[0][0]))
        result.add_ping_fail((ping_loop - int(out_result[0][0])))
        print test_str+" 发送 "+str(ping_loop)+"个包, 收到" + \
            out_result[0][0]+"个包, "+"失败率是："+out_result[0][1]
        if out_result[0][1] != "0":
            print(out_str)
        return True
    else:
        result.add_unknow_host(1)
        return False
